package com.atguigu.mall.search.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.mall.search.config.ElasticsearchConfig;
import com.atguigu.mall.search.constant.IndexConst;
import com.atguigu.mall.search.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

@Service
@Slf4j
public class ProductServiceImpl implements ProductService {

    @Resource
    private RestHighLevelClient restHighLevelClient;

    @Override
    public Boolean saveProductList(List<SkuEsModel> skuEsModels) throws IOException {
        boolean b =false;
        if (CollUtil.isNotEmpty(skuEsModels)){
            BulkRequest bulkRequest = new BulkRequest();
            for (SkuEsModel model : skuEsModels) {
                IndexRequest indexRequest = new IndexRequest(IndexConst.PRODUCT_INDEX);
                indexRequest.id(model.getSkuId().toString());
                String jsonModel = JSONUtil.toJsonStr(model);
                indexRequest.source(jsonModel, XContentType.JSON);
                bulkRequest.add(indexRequest);
            }
            BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, ElasticsearchConfig.COMMON_OPTIONS);
            //TODO 如果批量出错
             b = bulk.hasFailures();
            if (b){
                log.info("商品上架异常");
            }
            return !b;
        }
        return b;
    }
}
